package lj.jdbctest.jdbcS;

import lj.jdbctest.util.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

/**
 * @author lj
 * @Description: 登录
 * @date 2020-11-23 15:17
 * @QQ 851477108
 */


public class JDBCSign {
    public static void main(String[] args) {
        //1.键盘录入，接受用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        //2.调用方法
        Boolean flag = new JDBCSign().loginPS(username,password);
        //3.判断结果，输出不同语句
        if (flag){
            //登录成功
            System.out.println("登录成功!");
        }else {
            System.out.println("用户名或密码错误!");
        }
    }

    /**
     * 登录-判断用户是否存在
     * @param username
     * @param password
     * @return
     */
    public boolean login(String username,String password){
        if (username == null || password == null){
            return false;
        }
        //连接数据库判断是否登录成功
        Connection conn = null;
        Statement statement =  null;
        ResultSet rs = null;
        //1.获取连接
        try {
            conn = JDBCUtils.getConnection();
            //2.定义sql
            String sql = "select * from  user where username = '"+username+"' and '"+password+"'";
            //3.获取执行sql的对象
            statement = conn.createStatement();
            //4.执行查询
            rs = statement.executeQuery(sql);
            return rs.next();
        }
        catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs,statement,conn);
        }
        return false;
    }


    /**
     * 登录-判断用户是否存在使，用PreparedStatement实现
     * @param username
     * @param password
     * @return
     */
    public boolean loginPS(String username,String password){
        if (username == null || password == null){
            return false;
        }
        //连接数据库判断是否登录成功
        Connection conn = null;
        PreparedStatement ps =  null;
        ResultSet rs = null;
        //1.获取连接
        try {
            conn = JDBCUtils.getConnection();
            //2.定义sql
            String sql = "select * from  user where username = ? and password = ?";
            //3.获取执行sql的对象
            ps = conn.prepareStatement(sql);
            //给?赋值
            ps.setString(1,username);
            ps.setString(2,password);
            //4.执行查询
            rs = ps.executeQuery();
            return rs.next();
        }
        catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs,ps,conn);
        }
        return false;
    }
}
